package com.winforsys.yellowbook;
import java.io.StringReader;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.widget.Toast;


public class DataParser {

	public class Member {
		String number;
		String name;
		String group;
		String company;
		String department;
		String position;
		String email;
		String messenger;
		String cellphone;
		String telephone;
		String homephone;
		String company_address;
		String home_address;
		int image;
	}
	
	public Member[] GetMemberListFromXML (String xml) {
		
		ArrayList<Member> members = new ArrayList<Member>();
		
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = factory.newPullParser();
			parser.setInput(new StringReader(xml));
			
			int event = parser.getEventType();
			Member member = null;
			int cursor = 0;
			
			while (event != XmlPullParser.END_DOCUMENT) {
				switch (event) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.END_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					int depth = parser.getDepth();
					switch (depth)
					{
					case 2:
						member = new Member();
						cursor = 0;
						break;
					case 3:
						cursor++;
						break;
					}
					break;
				case XmlPullParser.END_TAG:
					if (parser.getDepth() == 2) {
						members.add(member);
					}
					break;
				case XmlPullParser.TEXT:
					if (parser.getDepth() == 3) {
						switch (cursor) {
						case 1: 
							member.number = parser.getText(); 
						break;
						case 2: 
							member.name = parser.getText(); 
						break;
						case 3: 
							member.group = parser.getText(); 
						break;
						case 4: 
							member.company = parser.getText(); 
						break;
						case 5: 
							member.department = parser.getText(); 
						break;
						case 6: 
							member.position = parser.getText(); 
						break;
						case 7: 
							member.email = parser.getText(); 
						break;
						case 8: 
							member.messenger = parser.getText(); 
						break;
						case 9: 
							member.cellphone = parser.getText(); 
						break;
						case 10: 
							member.telephone = parser.getText(); 
						break;
						case 11: 
							member.homephone = parser.getText(); 
						break;
						case 12: 
							member.company_address = parser.getText(); 
						break;
						case 13: 
							member.home_address = parser.getText(); 
						break;
						}
					}
					break;
				}
				
				event = parser.next();
			}
		}
		catch (Exception ex){
			String message = ex.getMessage();
			
			Toast.makeText(null, message, 0).show();
		}
		
		return members.toArray(new Member[members.size()]);
	}
}
